import sys
import os
import subprocess
from PyQt4.QtGui import QMessageBox

PROGRAMS_PATH_LIST = [
    r"C:\Program Files (x86)",
    r"C:\Program Files",
    r"D:\Program Files (x86)",
    r"D:\Program Files",
]

XDK_PATH = r"Microsoft Xbox 360 SDK\bin\win32"

XBDIR_PATH = "xbdir.exe"
XBCP_PATH  = "xbcp.exe"

def listDir(path, xbox=None):
    args = [XBDIR_PATH, "/b"]
    if xbox:
        args.append("/x:%s" % xbox)
    args.append(path)

    startupInfo = None
    if os.name == 'nt':
        startupInfo = subprocess.STARTUPINFO()
        startupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupInfo)
    stdout, stderr = proc.communicate()

    res = []
    for line in stdout.splitlines():
        line = line.strip()
        if line:
            res.append(line)

    err = stderr.strip()

    if not res and err:
        return None

    return res

def copy(src, dst, xbox=None):
    args = [XBCP_PATH, "/rsydtf"]
    if xbox is not None:
        args.append("/x:%s" % xbox)
    args.extend([src, dst])

    startupInfo = None
    if os.name == 'nt':
        startupInfo = subprocess.STARTUPINFO()
        startupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    return subprocess.Popen(args, stderr=subprocess.PIPE, startupinfo=startupInfo)

def _resolve_path(name):
    for programs_path in PROGRAMS_PATH_LIST:
        path = os.path.join(programs_path, XDK_PATH, name)
        if os.path.exists(path):
            return path

    return None

XBDIR_PATH = _resolve_path(XBDIR_PATH)
XBCP_PATH  = _resolve_path(XBCP_PATH)

if not XBDIR_PATH or not XBCP_PATH:
    QMessageBox.critical(None, "Error", "Please install Xbox360 SDK", QMessageBox.Ok)
    sys.exit(-1)